package com.rcadmin.busi.admin.action;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.rcadmin.busi.admin.ddl.SysUser;
import com.rcadmin.busi.admin.dto.LoginReq;
import com.rcadmin.busi.admin.service.SysUserService;
import com.rcadmin.core.app.action.ActionException;
import com.rcadmin.core.app.action.ResponseData;
import com.rcadmin.core.app.action.ResponseUtils;
import com.rcadmin.core.app.bean.UserInfo;
import com.rcadmin.core.app.session.SessionControl;
import com.rcadmin.core.web.BaseAction;

/**
 * 
 * @author tanson lam
 * @create 2016年10月2日
 */
@RestController
public class LoginRest extends BaseAction {
	private static Logger logger = LoggerFactory.getLogger(BaseAction.class);

	@Resource
	private SysUserService sysUserService;

	/**
	 * 用户登陆
	 * 
	 * @throws ActionException
	 */
	@RequestMapping(value = "/login.op", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData login(@RequestBody LoginReq loginReq)
			throws ActionException {
		ResponseData responseData;
		try {

			List<SysUser> userList = sysUserService.findUser(loginReq
					.getUserName());
			if (userList.isEmpty()) {
				responseData = ResponseUtils.fail("登陆失败！不存在该用户名称");
			} else {
				SysUser sysUser = userList.get(0);
				if (sysUser.getPassword().equals(loginReq.getPassword().trim())) {
					UserInfo userInfo = new UserInfo();
					BeanUtils.copyProperties(userInfo, sysUser);
					SessionControl.setUserInfo(request, userInfo);
					responseData = ResponseUtils.success("登陆成功！");
				} else {
					responseData = ResponseUtils.fail("登陆失败！密码不正确");
				}
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			responseData = ResponseUtils.fail("系統錯誤！" + e.getMessage());
		}
		return responseData;
	}

}
